package com.android.lovely.ui.viewmodel

import android.os.SystemClock
import androidx.lifecycle.viewModelScope
import com.android.lovely.api.LovelyException
import com.android.lovely.api.service.taskService
import com.android.lovely.api.service.userService
import com.android.lovely.data.CardWrapper
import com.android.lovely.data.SmartCreateState
import com.android.lovely.data.SmartRole
import com.android.lovely.framework.BaseViewModel
import com.android.lovely.framework.doContinuousOperation
import com.android.lovely.manager.UpLoadRoleManager
import com.android.lovely.room.role.CacheRoleServer
import com.android.lovely.room.role.CreateRole
import com.android.lovely.room.role.CreateRoleDataBase
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow

/**
 *
 * @author why
 * @date 2025/4/6 17:20
 */
class CreateRoleViewModel : BaseViewModel() {
    var id = SystemClock.elapsedRealtime().toInt()

    var isEdit = false
    var isQuick = false

    var createRole: CreateRole? = null

    private val _createRoleFlow = MutableSharedFlow<CreateRole>(0, 1, BufferOverflow.SUSPEND)
    val createRoleFlow: SharedFlow<CreateRole> get() = _createRoleFlow

    private val _cardPrice = MutableSharedFlow<CardWrapper>(0, 1, BufferOverflow.SUSPEND)
    val cardPrice: SharedFlow<CardWrapper> get() = _cardPrice

    private val _stepFlow = MutableSharedFlow<Int>(0, 1, BufferOverflow.SUSPEND)
    val stepFlow: SharedFlow<Int> get() = _stepFlow

    private val _quickCostFlow = MutableStateFlow(0)
    val quickCostFlow: StateFlow<Int> get() = _quickCostFlow

    private val _smartResultFlow = MutableSharedFlow<SmartCreateState>(extraBufferCapacity = 1)
    val smartResponseFlow: SharedFlow<SmartCreateState> get() = _smartResultFlow

    var last = false; private set

    private val creator get() = createRole?.let { UpLoadRoleManager(it) }
    fun initRole(id: Int, isEdit: Boolean, createRole: CreateRole) {
        viewModelScope.launchSafety {
            this@CreateRoleViewModel.id = id
            this@CreateRoleViewModel.isEdit = isEdit
            this@CreateRoleViewModel.createRole = createRole
            _createRoleFlow.emit(createRole)
        }
    }

    override fun onCleared() {
        super.onCleared()
        creator?.remove()
    }

    fun getCardPrice() {
        viewModelScope.launchSafety {
           val cardWrapper = userService.getProducerCardConfig()
            _cardPrice.emit(cardWrapper)
        }
    }

    fun updateRole(updateAction: CreateRole.() -> Unit) {
        createRole?.updateAction()
    }

    fun save() {
        viewModelScope.launchSafety {
            createRole?.let {
                CacheRoleServer.update(it)
                CreateRoleDataBase.dao.save(it)
            }
        }
    }

    fun nextStep(position: Int) {
        _stepFlow.tryEmit(position + 1)
    }

    fun preStep(position: Int) {
        _stepFlow.tryEmit(position - 1)
    }

    fun getSmartPrice() {
        viewModelScope.launchSafety {
            doContinuousOperation {
                _quickCostFlow.emit(userService.getSmartCost().getOrDefault("cost", 0))
            }
        }
    }

    private var job: Job? = null

    fun smartCancel() {
        job?.cancel()
    }

    fun quickGenerate() {
        if (job?.isActive == true) return
        job = viewModelScope.launchSafety {
            val result: SmartRole? = taskService.quickGenerate(
                mapOf(
                    "name" to (createRole?.nickName ?: ""),
                    "gender" to (createRole?.gender ?: 0),
                    "description" to (createRole?.introduction ?: ""),
                    "last" to last
                )
            )["role_detail"]
            _smartResultFlow.emit(result?.let {
                last = false
                updateRole {
                    scenario = it.scenario
                    firstMessage = it.firstMsg
                    chatExample = it.exampleChat
                    description = it.description
                    introduction = it.personality
                    gender = it.gender
                    nickName = it.name
                }
                save()
                SmartCreateState.Success
            } ?: SmartCreateState.ServerError)
        }.onError {
            _smartResultFlow.tryEmit(it.takeIf { it is LovelyException }?.let {
                SmartCreateState.ServerError
            } ?: let { last = true; SmartCreateState.HttpError })
        }
    }

    suspend fun createRole(): Boolean = creator?.executeCreation() ?: false



}